using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace SPGE
{
    public class AnimatedBackground : ABackground, ISimpleUpdatable
    {
        public override string Path
        { get; protected set; }
        public TimeSpan AnimationDuration
        { get; protected set; }

        protected float PercentDone
        { get; set; }
        protected TimeSpan StartTime
        { get; set; }
        protected bool Started
        { get; set; }

        public override Microsoft.Xna.Framework.Rectangle SourceRectangle
        {
            get
            {
                //only remporary
                int top = 0, height = Texture.Height, width = Texture.Width;

                if(Texture.Height >= GameContainer.Device.DisplayMode.Height)
                    top = (int)((1 - PercentDone) * (float)(Texture.Height - GameContainer.Device.DisplayMode.Height));

                if (height - top < GameContainer.Device.DisplayMode.Height)
                    top = height - GameContainer.Device.DisplayMode.Height;
                if (top < 0)
                    top = 0;

                return new Microsoft.Xna.Framework.Rectangle((Texture.Width - GameContainer.Device.PresentationParameters.BackBufferWidth) / 2, top,
                    width > GameContainer.Device.PresentationParameters.BackBufferWidth ? GameContainer.Device.PresentationParameters.BackBufferWidth : width,
                    height > GameContainer.Device.PresentationParameters.BackBufferHeight ? GameContainer.Device.PresentationParameters.BackBufferHeight : height);
            }
            set { /*Set is not used since we are goind to provide a simple animation for our background*/ }
        }

        public AnimatedBackground(string path, TimeSpan duration)
        {
            this.Path = path;
            AnimationDuration = duration;
            RenderLevel = 1f;
        }

        public override void Initialize()
        {
            Started = false;
            StartTime = TimeSpan.Zero;
        }

        public override void Load(ResourceGroupHandler group)
        {
            base.Load(group);

            Size = new Vector2(GameContainer.Device.PresentationParameters.BackBufferWidth, GameContainer.Device.PresentationParameters.BackBufferHeight);
        }

        public void Update(Microsoft.Xna.Framework.GameTime gameTime)
        {
            if(!Started)
            {
                StartTime = gameTime.TotalGameTime;
                Started=true;
            }

            PercentDone = (float)((gameTime.TotalGameTime.TotalSeconds - StartTime.TotalSeconds) / AnimationDuration.TotalSeconds);
        }
    }
}
